<template>
  <a-modal v-model:visible="visible" @cancel="cancelHandle" @ok="cancelHandle" style="min-width: 1050px">
    <div class="container">
      <a-row>
        <h3 style="font-weight: 600">音乐</h3>
      </a-row>
      <a-row>
        <a-col><a-input :bordered="false" @change="handleInputChange" v-model:value="material_name"
            style="background-color: #f4f5f5; width: 300px" placeholder="请搜索内容搜索歌曲" /></a-col>
      </a-row>
      <a-row>
        <a-tabs v-model:activeKey="activeTab" @change="changeTab">
          <a-tab-pane v-for="item in tabList" :key="item.id" :tab="item.name">
            <a-spin :spinning="spinning" style="height: 500px">
              <div class="music-list" v-if="musicList.length > 0">
                <div class="music-item" v-for="item in musicList" :key="item.id"
                  :style="{ borderColor: isSelected(item.id) ? '#2878FF' : '' }" @click="toggleItem(item)">
                  <div class="item-left">
                    <!-- 顶部播放按钮 -->
                    <span class="play-btn">
                      <!-- 播放 -->
                      <cu-icon type="icon-a-bofang1x1" @click.stop="playAudio(item)"
                        v-if="!isItemPlaying(item)"></cu-icon>
                      <!-- 暂停 -->
                      <cu-icon type="icon-a-zanting1x1" @click.stop="pauseAudio(item)" v-else></cu-icon>
                    </span>
                  </div>
                  <div class="item-right">
                    <div class="item-right-name">
                      <a-tooltip>
                        <template #title v-if="item.material_name.trim().length > 10">{{ item.material_name
                          }}</template>
                        {{ item.material_name }}
                      </a-tooltip>
                    </div>
                    <div class="item-right-time">
                      {{ item.material_duration_text }}
                    </div>
                  </div>
                  <a-checkbox class="checkbox" v-if="isSelected(item.id)" :checked="isSelected(item.id)"
                    @change="toggleItem(item)"></a-checkbox>
                  <div class="bottom_con">
                    <heart-outlined @click.stop="collectThis(item)"
                      :style="{ color: item.collect_count > 0 ? '#2878FF' : '#cccc' }" />
                  </div>
                </div>
              </div>
              <div class="music-list" v-else style="justify-content: center;">
                <a-empty/>
              </div>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
        <!-- 底部播放卡片 -->
        <div class="item-play-card" v-if="isShowBottomCard">
          <div class="play-card">
            <div class="card-left">
              <img src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" alt="" />
              <span class="play-btn">
                <caret-right-outlined v-if="!isBottomCardPlaying" @play="audioPlayIn"
                  @click="playAudio(activeMusicItem)" />
                <pause-outlined @click="pauseAudio(activeMusicItem)" v-else @pause="audioPauseIn" />
              </span>
            </div>
            <div class="card-right">
              <div class="card-right-top">
                {{ activeMusicItem.material_name }}
              </div>
              <div class="card-right-bottom">
                <audio ref="audioPlayer" controls name="media" class="audio" @play="audioPlayHandle"
                  @pause="audioPauseHandle" :src="activeMusicItem.material_url"></audio>
              </div>
              <div class="card-closebtn" @click="closeBottomCard">
                <close-outlined />
              </div>
            </div>
          </div>
        </div>
      </a-row>
    </div>

    <template #footer>
      <div style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
        <div>
          <a-button type="text" size="small" @click="selectItems">已选择{{ selectData?.length }}</a-button>
          <a-button type="link" size="small" @click="selectAll" v-show="selectData?.length !== musicList?.length && selectData?.length > 0
            ">全选</a-button>

          <a-button type="link" size="small" @click="deselectAll" v-show="selectData?.length > 0">全部取消</a-button>
        </div>
        <div>
          <a-button @click="cancelHandle">取消</a-button>
          <a-button type="primary" @click="handleOk">确定</a-button>
        </div>
      </div>
    </template>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  nextTick,
  onMounted,
  ref,
  defineEmits,
} from "vue";
import {
  CaretRightOutlined,
  PauseOutlined,
  CloseOutlined,
  HeartOutlined
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { useStore } from "vuex";
import _ from "lodash";
export default defineComponent({
  components: { CaretRightOutlined, PauseOutlined, CloseOutlined, HeartOutlined },
  props: {
    // 父组件当前操作的镜头组
    selectList: {
      type: Array,
    },
    selectData: {
      type: Array,
    },
  },

  setup(props, context) {
    const state = reactive({
      visible: false,
      activeTab: 7, //当前点击的tab,默认是热歌榜
      tabList: [], //tab列表
      musicList: [], //音乐列表
      spinning: false,
      musicItemIsChecked: false,

      isShowBottomCard: false, //底部播放卡片
      currentlyPlayingItem: null, //当前播放音乐
      material_name: "", //音乐名称，用于顶部搜索双向绑定
      isBottomCardPlaying: false, //底部按钮是否显示
      activeMusicItem: null, //当前选中的音乐对象
    });
    // 仓库
    const store = useStore();
    // 仓库中的混剪数据
    const VideoMashup = computed(() => {
      return store.state.videoMixCut.VideoMashup;
    });
    const selectData = ref([]);
    const showModal = () => {
      selectData.value = JSON.parse(JSON.stringify(props.selectList));
      state.visible = true; //打开弹窗
      getTabList();
      getMusicList();
    };

    // 全选取消全选
    const toggleChecked = (value) => {
      if (value) {
        selectData.value = state.musicList.map((item) => item.id);
      } else {
        selectData.value = [];
      }
    };
    // 判断是否选中
    const isSelected = (id) => {
      return selectData.value.includes(id);
    };
    // 切换高亮
    const toggleItem = (item) => {
      let index = selectData.value.findIndex((id) => id === item.id);
      isSelected(item.id)
        ? selectData.value.splice(index, 1)
        : selectData.value.push(item.id);
    };
    // 选中的音乐
    const selectItems = () => {
      console.log(selectData.value);
    };
    // 全选
    const selectAll = () => {
      selectData.value = state.musicList.map((ele) => ele.id);
    };
    // 取消全选
    const deselectAll = () => {
      selectData.value = [];
    };

    // 取消
    const cancelHandle = () => {
      state.visible = false;
      state.isPlaying = false;
      state.isShowBottomCard = false;
    };
    // 获取音乐列表
    const getMusicList = () => {
      state.spinning = true;
      state.isShowBottomCard = false;
      let params = {
        tag_id: state.activeTab,
        material_name: state.material_name,
      };
      request
        .get("/work_ai", "/user/shotstack/material/bgm/list", params)
        .then((res) => {
          state.musicList = res.result.length? res.result.map(ele => {
            return {
              ...ele,
              media_id: ele?.oss_media_id || ''
            }
          }) : []
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          state.spinning = false;
        });
    };
    // 获取tab栏列表
    const getTabList = () => {
      let params = {
        scene_type: "bgm",
      };
      request
        .get("/work_ai", "/user/shotstack/material/tags", params)
        .then((res) => {
          state.tabList = res.result;
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // tab栏切换
    const changeTab = (e) => {
      state.activeTab = e;
      getMusicList();
    };
    // 判断当前音乐是否在播放
    const isItemPlaying = (item) => {
      return item === state.currentlyPlayingItem;
    };

    // 开始播放
    const playAudio = (item) => {
      state.activeMusicItem = item;
      state.currentlyPlayingItem = item;
      state.isShowBottomCard = true;
      state.isBottomCardPlaying = true;
      nextTick(() => {
        const audioPlayer = document.querySelector(".audio");
        audioPlayer.play();
      });
    };
    // 停止播放
    const pauseAudio = (item) => {
      const audioPlayer = document.querySelector(".audio");
      audioPlayer.pause();
      state.currentlyPlayingItem = null;
      state.isBottomCardPlaying = false;
    };
    // 通过点击audio开启顶部和底部卡片播放按钮
    const audioPlayHandle = () => {
      state.currentlyPlayingItem = state.activeMusicItem;
      state.isBottomCardPlaying = true;
    };
    // 通过点击audio开启顶部和底部卡片播放按钮
    const audioPauseHandle = () => {
      state.currentlyPlayingItem = null;
      state.isBottomCardPlaying = false;
    };
    // 关闭底部播放悬浮卡片
    const closeBottomCard = () => {
      state.isShowBottomCard = false;
      state.currentlyPlayingItem = null;
      state.isBottomCardPlaying = false;
    };
    // 防抖
    const debounce = (func, wait = 2000, immediate = false) => {
      if (state.timeout !== null) clearTimeout(state.timeout);
      // 立即执行，此类情况一般用不到
      if (immediate) {
        typeof func === "function" && func();
      } else {
        // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
        state.timeout = setTimeout(function () {
          typeof func === "function" && func();
        }, wait);
      }
    };
    // 输入框change事件
    const handleInputChange = (e) => {
      debounce(() => {
        getMusicList();
      });
    };
    // 确定
    const handleOk = () => {
      state.visible = false;
      state.isShowBottomCard = false;
      console.log(selectData.value, "提交");
      const selects = state.musicList.filter((ele) => {
        return selectData.value.includes(ele.id);
      });
      console.log(selects, "selects");
      context.emit("updataMusic", selects);
    };
    // 收藏
    const collectThis = (ele) => {
      request
        .put("/work_ai", "/user/shotstack/material/collect", {
          material_id: ele.id,
          scene_type: ele.scene_type == "audio" ? "bgm" : ele.scene_type,
          is_collect: ele.collect_count == 0 ? 1 : 0,
        })
        .then((res) => {
          // console.log(res)
          getMusicList()
        });
    };
    return {
      ...toRefs(state),
      showModal,
      handleOk,
      changeTab,
      getMusicList,
      getTabList,
      cancelHandle,
      selectItems,
      selectAll,
      deselectAll,
      toggleItem,
      toggleChecked,
      isSelected,
      playAudio,
      pauseAudio,
      isItemPlaying,
      debounce,
      handleInputChange,
      closeBottomCard,
      audioPlayHandle,
      audioPauseHandle,
      VideoMashup,
      selectData,
      collectThis
    };
  },
});
</script>

<style lang="less" scoped>
.music-list {
  max-height: 500px;
  min-width: 1000px;
  display: flex;
  flex-wrap: wrap;
  overflow-y: auto;
  position: relative;

  &::-webkit-scrollbar {
    width: 6px;
    background: #fafafa;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  .music-item {
    width: 30%;
    margin: 15px 15px 0 0;
    height: 80px;
    background: rgb(244, 245, 245);
    border: 1px solid #ededed;
    border-radius: 10px;
    display: flex;
    position: relative;
    cursor: pointer;

    &:nth-child(3n) {
      margin-right: 0;
    }

    .item-left {
      width: 30%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      // background: skyblue;
      .play-btn {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 50px;
        height: 50px;
        transform: translate(-50%, -50%);
        // background: rgba(0, 0, 0, 0.7);
        // border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 40px;
        color: #cccc;
        // visibility: hidden;
      }
    }

    .item-right {
      flex: 1;
      width: calc(100% - 100px);
      padding: 10px 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      color: black;

      .item-right-name {
        width: 100%;
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 超出部分隐藏 */
        text-overflow: ellipsis;
        /* 使用省略号代表被隐藏的文本 */
      }

      // .item-right-time {
      //   color: #cccc;
      // }
    }

    .checkbox {
      position: absolute;
      top: -4px;
      right: -2px;
    }

    .bottom_con {
      position: absolute;
      bottom: 3px;
      right: 5px;
      font-size: 16px;
    }

    // &:hover {
    //   border-color: rgb(255, 101, 98);
    //   .play-btn {
    //     visibility: visible;
    //   }
    // }
  }
}

// 底部播放卡片
.item-play-card {
  visibility: hidden;
  position: fixed;
  display: flex;
  justify-content: center;
  left: 50%;
  transform: translateX(-50%);
  bottom: 140px;
  width: 800px;
  height: 100px;
  z-index: 9999;

  .play-card {
    width: 90%;
    height: 100px;
    border-radius: 5px;
    padding: 10px 20px;
    display: flex;
    background: #fff;
    align-items: center;
    border: 1px solid #e5e5e5;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    cursor: pointer;

    .card-left {
      width: 70px;
      height: 70px;
      margin-right: 10px;
      position: relative;

      .play-btn {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 25px;
        height: 25px;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
        color: #fff;
        z-index: 9999;
        // visibility: hidden;
      }

      img {
        width: 70px;
        height: 70px;
        border-radius: 5px;
      }
    }

    .card-right {
      height: 70px;
      flex: 1;
      padding-left: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      position: relative;

      .card-right-top {
        font-weight: 600;
        font-size: 16px;
      }

      .card-right-bottom {
        display: flex;
        align-items: center;
        justify-content: space-between;

        audio {
          height: 30px;
          width: 90%;
        }
      }

      .card-closebtn {
        position: absolute;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        background: rgb(243, 243, 244);
        color: rgb(255, 101, 98);
        font-weight: 600;
        right: 0;
        top: 0;
      }
    }
  }
}
</style>
